<?php
/**
 * 租赁签约相关
 * User: banjin
 * Date: 17-1-23
 * Time: 上午10:04 
 */
namespace app\backend\controller;

use app\backend\controller\traits\AuthManager;
use app\backend\model\BillManager;
use app\backend\model\MessageTemplate;
use app\backend\model\PayNotice;
use app\backend\model\Photo;
use app\backend\model\Trust;
use think\Controller;
use app\backend\model\Member;
use app\backend\model\Lease;
use app\backend\model\Contract;
use think\Exception;
use app\backend\model\Building;

class LeaseController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }


    /**
     * 获取我的合同
     * @date   2017-01-18
     * @author wuhao
     *
     * @param int  $page      页数
     * @param int  $pageSize 每页个数
     * @return
     */
    public function index()
    {
        if (!in_array($this->getOper('lease_list'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $page     = I('page', 1, 'intval');
        $pageSize = I('page_size', 10, 'intval');

        try {
            if (!is_numeric($page) || $page<=0) {
                throw new Exception("参数错误!", 400);
            }
            $contractModel = new Lease();
            $res           = $contractModel->getMyLease($this->_pmid, $this->_pdtype, $page, $pageSize);
            if (!$res) {
                throw new Exception("暂无数据！", 201);
            } else {
                //合同里的楼宇id数组和合同编号数组
                $buildId = array_unique(array_column($res['list'], 'building_id'));
                //获取对应的楼宇信息
                $buildModel = new Building();
                $buildInfo  = $buildModel->getBuildingList(['id' => ['in', $buildId], 'is_delete' => 0], 'id, province, city, country, name, address');
                //获取租户名称电话
                $tenantId    = array_column($res['list'], 'tenant_id');
                $memberModel = new Member();
                $tenantInfo  = $memberModel->getMemberInfo(['id' => ['in', $tenantId], 'status' => 1], 'id, nickname, mobile');
                $orderNum    = array_column($res['list'], 'ordernum');
                //获取对应的房源
                $leaseModel = new Lease();
                $room      = $leaseModel->getLeaseExtByOrderNum($orderNum, 'ordernum, room');

                foreach ($res['list'] as $k => $v) {
                    //添加倒计时功能
                    $res['list'][$k]['countdown'] = round((strtotime($v['end_time']) - time()) / 86400);
                    //时间格式
                    $res['list'][$k]['begin_time'] = date('Y-m-d', strtotime($v['begin_time']));
                    $res['list'][$k]['end_time']   = date('Y-m-d', strtotime($v['end_time']));
                    foreach ($buildInfo as $b) {//楼宇信息
                        if ($v['building_id'] == $b['id']) {
                            $res['list'][$k]['province'] = $b['province'];
                            $res['list'][$k]['city']     = $b['city'];
                            $res['list'][$k]['country']  = $b['country'];
                            $res['list'][$k]['name']     = $b['name'];
                            $res['list'][$k]['address']  = $b['address'];
                            break;
                        }
                    }
                    foreach ($tenantInfo as $t) {//租户信息
                        if ($v['tenant_id'] == $t['id']) {
                            $res['list'][$k]['username'] = $t['nickname'];
                            $res['list'][$k]['mobile']   = $t['mobile'];
                            break;
                        }
                    }
                    foreach ($room as $r) {
                        if ($v['ordernum'] == $r['ordernum']) {
                            $res['list'][$k]['room']   = $r['room'];
                            break;
                        }
                    }
                }
                $msg  = '查询成功';
                $code = 200;
            }
        } catch (Exception $e) {
            $msg  = $e->getMessage();
            $code = $e->getCode();
        }

        $this->apiReturn($code, $res, $msg);
    }

    /**
     * 获取合同编号查看相关合同信息
     * @date   2017-1-23
     * @author banjin
     *
     * @param  int  $ordernum    合同编号
     *
     * @return json
     */
    public function getMycontractInfo()
    {
        $ordernum      = I('ordernum', '', 'strval');
        if (!$ordernum) {
            $this->apiReturn(400, [], '参数错误');
        }

        $leaseModel  = new Lease();
        $memberModel = new Member();
        $data        = $leaseModel->getLeaseDetail($ordernum);//获取基本信息
        if ($data) {
            //获取租户信息
            $tenantInfo = $memberModel->getMemberInfo(['id' => $data['tenant_id']], 'username, mobile, nickname tenant_name, id_card, license, sex, address');
            $data['tenant_name'] = $tenantInfo[0]['tenant_name'];
            $data['username']    = $tenantInfo[0]['username'];
            $data['zmobile']     = $tenantInfo[0]['mobile'];
            $data['id_card']     = $tenantInfo[0]['id_card'];
            $data['sex']         = $tenantInfo[0]['sex'];
            $data['license']     = $tenantInfo[0]['license'];
            $data['address']     = $tenantInfo[0]['address'];

            //获取对应的房源信息, 托管状态
            $extData      = $leaseModel->getLeaseExtByOrderNum($ordernum, 'house_number, room');
            $houseNumbers = array_column($extData, 'house_number');
            $buildModel   = new Building();
            $houseInfo    = $buildModel->getHouseList(['house_number' => ['in', $houseNumbers]],
                'mid, trust_status,house_number, room, price_type, price, price_power, price_water, fee_power, fee_water, area, property');
            $trustStatus  = array_unique(array_column($houseInfo, 'trust_status'));
            $mid          = array_unique(array_column($houseInfo, 'mid'));

            /*if (count($trustStatus) >1 || count($mid) >1) {
                //存在有托管和没托管的房源   房源业主超过1个,错误
                $this->apiReturn(400, [], '房源信息有误');
            }*/
            if ($trustStatus[0] == 1) {
                $trustModel = new Trust();
                $trustInfo  = $trustModel->getTrustId($mid[0], $data['building_id']);  //托管方id
                $trustId    = $trustInfo['trust_id'];
            } else {
                $trustId = 0;
            }
            $feeData = [];
            //基本的房租，物业费(每月), 水电(单价)等
            foreach ($houseInfo as $h) {
                $tmpData['rent_price'] = ($h['price_type'] == 0) ? yuan($h['price']) : yuan($h['price'] * $h['area']);//0=按月 1=按每平米
                $tmpData['property'] =  yuan($h['property'] * $h['area']);
                $tmpData['water'] = yuan($h['price_water']);
                $tmpData['power'] = yuan($h['price_power']);
                $tmpData['gt_water'] =  yuan($h['fee_water']);
                $tmpData['gt_power'] =  yuan($h['fee_power']);
                $tmpData['room'] =  $h['room'];
                $tmpData['house_number'] = $h['house_number'];
                $feeData[] = $tmpData;
                unset($tmpData);
            }


            //获取收费对象信息
            $userId = $buildModel->getContractFeeB($data['building_id']);
            $operator   = $userId['mid'];  //运营方id
            $property   = $userId['property_id'];  //物业公司id
            $hydropower = $userId['hydropower_id'];  //水电公司id
            $feeId = [
                'mid'        => $mid[0],
                'trust_id'   => $trustId,
                'operator'   => $operator,
                'property'   => $property,
                'hydropower' => $hydropower
            ];

            //税率,增长率及折扣率
            $data['tax'] = round($data['tax'] / 100, 2);
            $data['growth_rate'] = json_decode($data['growth_rate'], true);
            $data['discount']    = round($data['discount'] / 100, 2);
            $info = [
                'list' => $data,
                'room' => $extData,
                'fee'  => $feeData,
                'type' => 1,   //$type  1 合约生效
                'feeId'=> $feeId,
            ];
            $this->apiReturn(200, $info, '成功');
        } else {
            $this->apiReturn(200, [], '未查到数据');
        }
    }

    /**
     * 使合约失效
     * @date   2017-4-5
     * @author wuhao
     *
     * @param  string  $ordernum    合同编号
     * @param  int     $status      合同状态 0=失效
     *
     * @return json
     */
    public function forbidLease()
    {
        if (!in_array($this->getOper('forbid_lease'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $ordernum  = I('post.ordernum', '', 'strval');
        $status    = I('post.status', -1, 'intval');

        if (!$ordernum || !in_array($status, [0])) {
            $this->apiReturn(400, [], '参数错误');
        }

        $leaseModel = new Lease();
        //判断合同状态
        $leaseInfo = $leaseModel->getContractInfo(['ordernum' => $ordernum], 'id, create_user, status');
        if (!$leaseInfo) {//找不到合约信息
            $this->apiReturn(202, [], '没有相应的合同信息');
        }
        if ($this->_pmid != $leaseInfo[0]['create_user']) {//不是录入人
            $this->apiReturn(203, [], '无权操作');
        }
        if ($status == $leaseInfo[0]['status']) {//当前状态已经是想要修改的状态了
            $this->apiReturn(204, [], '合约已失效,无需重复修改');
        }

        $extData = $leaseModel->getLeaseExtByOrderNum($ordernum, 'house_number');
        $extData = array_column($extData, 'house_number');

        //使合约失效
        $res = $leaseModel->forbidLease($ordernum, $status);
        if ($res) {
            //使对应的租赁账单失效
            $billModel = new BillManager();

            $upstate = $billModel->updatePayBill(['ordernum' => $ordernum, 'is_delete' => 0], ['is_delete' => 1]);//将未支付的账单也更新为失效状态
            if (!$upstate) {
                zft_log('bill/lease_bill', $billModel->getLastSql());
            }

            //拓展表合同信息失效
            $forbid = $leaseModel->forbidExtLease($ordernum, $status);
            if (!$forbid) {
                zft_log('bill/update_lease_ext', $leaseModel->getLastSql());
            }

            //删除对应的用户催缴信息
            $payNoticeModel = new PayNotice();
            $notice = $payNoticeModel->deleteTemplate($ordernum);
            if (!$notice) {
                zft_log('notice/delete', $payNoticeModel->getLastSql());
            }

            //是房源状态更新为未出租的状态
            $buildModel = new Building();
            $updateHouse = $buildModel->updateHouse(['status' => 2], ['house_number' => ['in', $extData]]);
            if (!$updateHouse) {
                zft_log('bill/lease_bill_update_house', $buildModel->getLastSql());
            }
            $this->apiReturn(200, [], '操作成功');
        } else {
            zft_log('lease/update_lease', $leaseModel->getLastSql());
            $this->apiReturn(205, [], '操作失败,请稍后再试');
        }
    }

    /**
     * 根据合法的房源编号数组获取相关租赁的收费信息
     * @author banjin
     * @date   2017-01-24
     *
     * @param  array  $houseId      房源编号数组
     * @param  int    $buildingId   楼宇id
     *
     * @return json
     */
    public function findHouseInfo()
    {
        $houseId     = I('post.houseId');
        $buildingId  = I('post.building_id', '', 'intval');
        $houseId = json_decode($houseId, true);

        if (!$houseId || !is_array($houseId) || !$buildingId) {
            $this->apiReturn(400, [], '参数错误');
        }

        $buildModel = new Building();
        $trustModel = new Trust();
        $data   = $buildModel->getHouseList(['house_number' => ['in', $houseId]], 'mid, trust_status, price_type, price, area, property');

        $mid    = $data[0]['mid'];               //业主id
        $trustStatus = $data[0]['trust_status']; //托管状态为1表示托管中
        if ($trustStatus == 1) {
            $trust_ids = $trustModel->getTrustId($mid, $buildingId);  //托管方id
            $trust_id  = $trust_ids['trust_id'];
        } else {
            $trust_id = 0;
        }
        $dataSmall  = $buildModel->getContractFeeB($buildingId);
        $operator   = $dataSmall['mid'];  //运营方id
        $property   = isset($dataSmall['property_id']) ? $dataSmall['property_id'] : 0;  //物业公司id
        $hydropower = isset($dataSmall['hydropower_id']) ? $dataSmall['hydropower_id'] : 0;  //水电公司id
        $feeInfo = [];
        if ($data) {
            $houseMoney = $propertyMoney = 0;
            foreach ($data as $k => $v) {
                $priceType = $v['price_type'];//@wuhao  房租收费类型 0=按月 1=按平方米
                $houseMoney  += ($priceType == 0) ? ($v['price']) : ($v['area'] * $v['price']);
                $propertyMoney  += $v['area'] * $v['property'];
            }
            $houseMoney = round($houseMoney / 100, 2);
            $propertyMoney = round($propertyMoney / 100, 2);
            $hMoney = [
                'type'       => 1,
                'name'       => "房租",
                'mid'        => $mid,
                'trust_id'   => $trust_id,
                'operator'   => $operator,
                'property'   => $property,
                'hydropower' => $hydropower,
                'money'      => $houseMoney,
            ];
            $feeInfo[] = $hMoney;

            if ($propertyMoney != 0) {//物业费为0的删除
                $pMoney = [
                    'type'       => 2,
                    'name'       => "物业",
                    'mid'        => $mid,
                    'trust_id'   => $trust_id,
                    'operator'   => $operator,
                    'property'   => $property,
                    'hydropower' => $hydropower,
                    'money'      => $propertyMoney,
                ];
                $feeInfo[] = $pMoney;
            }
            
            $this->apiReturn(200, $feeInfo, '成功');
        } else {
            $this->apiReturn(400, [], '失败');
        }
    }

    /**
     * 处理导入的合同
     */
    public function handleImportOrder()
    {

        if (!in_array($this->getOper('handle_import'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $ordernum      = I('post.ordernum', '', 'strval');
        $useBillingDay = I('post.use_billing_day', 0, 'intval'); //是否按账单日生成账单
        $idCardA       = I('post.id_card_a', '', 'strval');     //身份证正面
        $idCardB       = I('post.id_card_b', '', 'strval');     //身份证反面
        $contractTime  = I('post.contract_time', '', 'strval');   //签约时间 20170515
        $tax           = I('post.tax', 0, 'floatval');          //税,默认为0
        $legalIdCard   = I('post.legal_id_card', '', 'strval'); //法人身份证信息
        $financeUser   = I('post.finance_user', '', 'strval');   //财务联系人名字
        $discount      = I('post.discount', 10, 'floatval');     //第一年折扣 默认10折(不打折)
        $photo         = I('post.photo', '', 'strval');         //租赁合约附件
        $growthRate    = I('post.growth_rate');                 //逐年增长率数组
        $houseNumber   = I('post.house_number');                //房源编号数组
        $feeInfo       = I('post.feeInfo');                     //合约费用数组
        $meter         = I('post.meter');                       //水电度数数组
        $type          = I('post.type', 0, 'intval');           //0=预览 1=提交
        if ($type == 1) {
            $billData      = I('post.bill_data');                   //账单的数据
            $billData      = json_decode($billData, true);
        }


//        $ordernum='149861671000';
//        $idCardA=$idCardB='555';
//        $financeUser='cs';
//        $contractTime='20170601';
//        $discount=10;
//        $tax=0;
//        $useBillingDay=1;
//        $feeInfo=[['fee'=>6091.2,'owner_id'=>32, 'type'=>1, 'ratio'=>100], ['fee'=>423,'owner_id'=>32, 'type'=>2, 'ratio'=>100]];
//        $meter = [['house_number'=>8513302, 'water'=>10, 'power'=>10]];
//        $houseNumber = ['8513302'];
//        $growthRate = [10,15];

        $growthRate    = json_decode($growthRate, true);
        $houseNumber   = json_decode($houseNumber, true);
        $feeInfo       = json_decode($feeInfo, true);
        $meter         = json_decode($meter, true);
        //dd($ordernum, $idCardB, $idCardA, $financeUser, $feeInfo, $houseNumber);

        if (!$ordernum || !$idCardA ||!$idCardB ||!$financeUser ||!$feeInfo
            ||!is_array($feeInfo) || !$houseNumber) {
            $this->apiReturn(202, [], '缺少参数或参数有误');
        }
        if (!$contractTime || !strtotime($contractTime)) {
            $this->apiReturn(202, [], '签约时间必填');
        }
        if (!is_numeric($discount) || $discount <=0 || $discount>10) {
            $this->apiReturn(202, [], '折扣值有误');
        }
        if ($type == 1 && !$billData) {
            $this->apiReturn(202, [], '请选择要生成的账单');
        }

        if (1 != count($meter)) {//房子和其对应的水电度数个数不一致
            $this->apiReturn(202, [], '水电度数有误');
        } else {
            //水电度数里的房源编号与房源编号比较
            $mHouse = array_column($meter, 'house_number');
            if ($mHouse[0] != $houseNumber) {
                $this->apiReturn(202, [], '水电度数有误');
            }
            foreach ($meter as $k => $m) {
                if (!is_numeric($m['house_number']) || !is_numeric($m['water']) || !is_numeric($m['power']) || $m['water'] <0 || $m['power']<0 || $m['house_number'] <0) {
                    $this->apiReturn(202, [], '水电度数有误');
                }
                $meter[$k]['water'] = round($m['water'] * 100);//乘以100取整
                $meter[$k]['power'] = round($m['power'] * 100);
            }
        }

        $leaseModel = new Lease();
        //获取已有的基本信息
        $orderDetail = $leaseModel->getImportOrderDetail($ordernum);
        $tenantId    = $orderDetail['tenant_id'];
        $beginTime   = $orderDetail['begin_time'];
        $endTime     = $orderDetail['end_time'];
        $freeDay     = $orderDetail['free_day'];
        $chargeType  = $orderDetail['charge_type'];
        $billingDay  = $orderDetail['billing_day'];
        $buildingId  = $orderDetail['building_id'];

        //判断这些房源是否已经签约
        $check = $leaseModel->getLeaseExtByHouse($houseNumber, 'id');
        if ($check) {
            $this->apiReturn(202, [], '存在房源已经签约过的了');
        }

        //检查租户信息的正确性
        $memberModel = new Member();
        $memberInfo = $memberModel->getMemberInfo(['id' => $orderDetail['tenant_id'], 'dtype' => 2], 'id, user_type');
        if (!$memberInfo) {
            $this->apiReturn(203, [], '输入的租户信息有误');
        }

        if ((strtotime($endTime) - (strtotime($beginTime.'+'.$freeDay.'day'))) <0) {
            $this->apiReturn(205, [], '租赁时间有误');
        }

        //开始周期作为起租日
        $beginRent = $beginTime;
        //获取合约时间长度, 判断合约时间是否合法
        $begin = date('Y-m-d', strtotime($beginRent));
        $end   = date('Y-m-d', strtotime($endTime));

        $diffDate = diffDate($begin, $end);//得到相隔年月日
        if ($diffDate['year'] >= 10) {
            $this->apiReturn(204, [], '租期不能超过10年');
        }
        //相隔年数, 月数, 季度数, 半年数
        $diffYear = $diffDate['year'] + 1;

        if ($diffYear >= 2) {
            //判断增长率是否合法
            if (!$growthRate || !is_array($growthRate) || (count($growthRate) != ($diffYear - 1))) {
                $this->apiReturn(205, [], '增长率不合法');
            }
            foreach ($growthRate as $k => $g) {
                if (!is_numeric($g) || $g < 0) {
                    $this->apiReturn(205, [], '增长率不合法');
                }
                $growthRate[$k] = intval($g*100);//增长率*100, 保存为整数
            }
        } else {
            $growthRate = [];
        }

        //判断基础费用设置
        $tmpRatio = $feeDataInfo = [];
        foreach ($feeInfo as $key => $value) {
            if ($value && $value['fee'] >=0 && $value['owner_id'] >0 && in_array($value['type'], [1,2]) && $value['ratio'] >0 && $value['ratio'] <=100) {
                $feeDataInfo[] = [
                    'ordernum' => $ordernum,
                    'fee'      => $value['fee']*100,
                    'owner_id' => $value['owner_id'],
                    'type'     => $value['type'],
                    'ratio'    => $value['ratio'],
                ];
                if (!isset($tmpRatio[$value['type']])) {//判断比例之和是否为100
                    $tmpRatio[$value['type']] = $value['ratio'];
                } else {
                    $tmpRatio[$value['type']] += $value['ratio'];
                }
            } else {
                $this->apiReturn(400, [], '费用设置有误!');
            }
        }

        foreach ($tmpRatio as $k => $v) {
            if ($v != 100) {
                $this->apiReturn(400, [], '费用比例设置有误!');
            }
        }
        $buildModel = new Building();
        //获取房源信息
        $houseList   = $buildModel->getHouseList(['house_number' => $houseNumber],
            'status, trust_status, building_id, mid, price, price_type, area, property');
        //判断这些费用与对应的房源的费用是否一致
        $rentMoney = $propertyMoney = 0;
        foreach ($houseList as $h) {
            if ($h['price_type'] == 0) {//按月
                $rentMoney += $h['price'];
            } else {//按每平米
                $rentMoney += $h['price'] * $h['area'];
            }
            $propertyMoney += $h['property'] * $h['area'];
        }
        foreach ($feeDataInfo as $f) {
            if ($f['type'] ==1 && $f['fee'] != $rentMoney) {//房租
                $this->apiReturn(400, [], '房租信息不匹配!');
            }
            if ($f['type'] ==2 && $f['fee'] != $propertyMoney) {//房租
                $this->apiReturn(400, [], '物业费信息不匹配!');
            }
        }

        //有配置税率的话
        if ($tax) {
            if (!is_numeric($tax) || $tax <0 || $tax>50) {
                $this->apiReturn(400, [], '税率配置有误!');
            }
            $tax = round($tax, 2) * 100;//税*100, 保存整数
            $taxArr = [];
            foreach ($feeDataInfo as $a => $item) {
                if ($item['type'] == 1) {//税费的收费对象和房租的一致
                    $taxArr[] = [
                        'fee'      => $item['fee'] * $tax / 10000 ,//生成每个月的单价
                        'type'     => 7,
                        'owner_id' => $item['owner_id'],
                        'ratio'    => $item['ratio'],
                        'ordernum' => $ordernum,
                    ];
                }
            }
            $feeDataInfo = array_merge($feeDataInfo, $taxArr);
        }

        //折扣乘以100,保存为整数
        $discount = round($discount * 100);
        //根据基础的费用生成每个周期的费用
        if ($useBillingDay == 1) {//按账单日生成
            $feeAllInfo = $this->_generateFeeByBillingDay($feeDataInfo, $chargeType, $freeDay, $begin, $end, $discount, $growthRate, $billingDay);
        } else {//每月递增生成
            $feeAllInfo = $this->_generateFee($feeDataInfo, $chargeType, $freeDay, $begin, $end, $discount, $growthRate);
        }

        if (!$feeAllInfo) {
            $this->apiReturn(400, [], '费用信息生成失败');
        }
        if ($type == 0) {//预览
            $returnData = $this->_previewBill($feeInfo, $feeAllInfo, $memberModel);
            foreach ($returnData as $k => $v) {
                $returnData[$k]['id'] = $k;
            }
            $this->apiReturn(200, $returnData, '');
        } else {//生成账单数据


            //先判断传入的账单数据格式
            foreach ($billData as $bill) {
                if (!is_numeric($bill['fee']) || $bill['fee']<0 || !is_numeric($bill['id'])) {
                    $this->apiReturn(400, [], '所传账单数据有误');
                }
            }

            //获取要插入的账单数据
            $insertBill = [];
            //将修改的金额替换
            foreach ($feeAllInfo as $k => $v) {
                foreach ($billData as $b) {
                    if ($b['id'] == $k) {//满足条件替换费用
                        $feeAllInfo[$k]['fee'] = fen($b['fee']);
                        $insertBill[] = $feeAllInfo[$k];
                        break;
                    }
                }
            }

            $updateData = [
                'status'        => 1,
                'id_card_a'     => $idCardA,
                'id_card_b'     => $idCardB,
                'finance_user'  => $financeUser,
                'legal_id_card' => $legalIdCard,
                'tax'           => $tax,
                'growth_rate'   => json_encode($growthRate),
                'discount'      => $discount,
                'contract_time' => $contractTime
            ];
            //更新这条合约的信息
            $res = $leaseModel->updateContract(['ordernum' => $ordernum], $updateData);
            if (!$res) {
                zft_log('lease_update', $leaseModel->getLastSql());
                $this->apiReturn(400, [], '账单状态更新失败');
            }

            //更新水电度数
            $resExt = $leaseModel->updateContractExt(['house_number'=>$meter[0]['house_number']],
                ['water' => $meter[0]['water'], 'electric' => $meter[0]['power'], 'status' => 1]);
            if (!$resExt) {
                zft_log('lease_update', $leaseModel->getLastSql());
            }

            //插入费用信息
            $feeRes = $leaseModel->insertFeeInfo($insertBill);
            if (!$feeRes) {
                zft_log('lease/add_lease_fee', $leaseModel->getLastSql());
                $this->apiReturn(400, [], '费用信息保存失败');
            }

            //图片信息的保存
            if ($photo) {
                $photos = explode(',', $photo);
                $photoModel = new Photo();
                $photoInfos = [];
                foreach ($photos as $val) {
                    $photoInfos[] = [
                        'rid'         => $orderDetail['id'],
                        'rtype'       => 3,
                        'srtype'      => 1,
                        'url'         => $val,
                        'create_user' => $this->_pmid,
                        'create_time' => time(),
                    ];
                }
                $resPhoto = $photoModel->addAll($photoInfos);
                if (!$resPhoto) {
                    zft_log('photo/add_lease', $photoModel->getLastSql());
                }
            }

            //把账单生成出来
            $bill = $this->_generateBill($ordernum);
            if (!$bill) {
                $this->apiReturn(400, [], '账单生成失败');
            }
            //插入账单数据
            $billModel = new BillManager();
            $billRes   = $billModel->insertPayBill($bill);
            if (!$billRes) {
                zft_log('lease/add_bill', $billModel->getLastSql());
                $this->apiReturn(400, [], '账单生成失败');
            }

            //再生成对应的催缴用户信息模板
            $messageModel = new MessageTemplate();
            $baseTmp      = $messageModel->getTemplateByPayOrIncome(1, 1, 1);//租赁账单 催缴 付款人,获取基本的模板信息
            if (!$baseTmp) {
                zft_log('message/get', $messageModel->getLastSql());
                $this->apiReturn(400, [], '用户消息模板保存失败');
            }
            //dd($baseTmp);
            $payNoticeModel = new PayNotice();
            $payNoticeData = $insertNotice = [];
            $tmp = [];
            foreach ($bill as $b) {
                //同一个时段一个用户, 重复的去掉
                $t = [$tenantId, $b['begin_cycle'], $b['end_cycle']];
                if (in_array($t, $tmp)) {
                    continue;
                } else {
                    $tmp[] = $t;
                    $payNoticeData[] = [
                        'mid'           => $tenantId,
                        'building_id'   => $buildingId,
                        'tmp_id'        => $baseTmp[0]['id'],
                        'ordernum'      => $ordernum,
                        'begin_cycle'   => $b['begin_cycle'],
                        'end_cycle'     => $b['end_cycle'],
                        //'mobile'        => $orderDetail['finance_mobile'],
                        'report_time'   => strtotime($b['begin_cycle']) - 86400 * $baseTmp[0]['notify_day'],
                        'priority'      => 1,
                        'status'        => 0,
                    ];
                }
                unset($t);
            }

            foreach ($payNoticeData as $pt) {
                if (strtotime($pt['end_cycle']) >= time()) {//比当前时间大的才加入催缴列表
                    $insertNotice[] = $pt;
                }
            }
            if ($insertNotice) {
                $res = $payNoticeModel->addAll($insertNotice);
                if (!$res) {
                    zft_log('payNotice/addTemplate', $payNoticeModel->getLastSql());
                    $this->apiReturn(400, [], '用户消息模板保存失败');
                }
            }

            $this->apiReturn(200, [], '账单生成成功');
        }
    }

    /**
     * 预览费用列表
     * @param $feeInfo 基础费用信息
     * @param $feeAllInfo 生成的费用信息
     * @param Member $memberModel 用户模型
     */
    private function _previewBill($feeInfo, $feeAllInfo, Member $memberModel)
    {
        //获取收款方信息
        $ownerIdArr = [];
        foreach ($feeInfo as $fi) {
            if (!in_array($fi['owner_id'], $ownerIdArr)) {
                $ownerIdArr[] = $fi['owner_id'];
            }
        }
        $ownerInfo = $memberModel->getMemberInfoById($ownerIdArr, 'id, nickname');
        $returnData = [];
        $count = count($feeAllInfo);
        for ($i = 0; $i< $count; $i++) {
            $nickname = '';
            foreach ($ownerInfo as $o) {
                if ($o['id'] == $feeAllInfo[$i]['owner_id']) {
                    $nickname = $o['nickname'];
                    break;
                }
            }
            $returnData[] = [
                'ordernum'   => $feeAllInfo[$i]['ordernum'],
                'type'       => $feeAllInfo[$i]['type'],
                'owner_id'   => $feeAllInfo[$i]['owner_id'],
                'nickname'   => $nickname,
                'begin_date' => $feeAllInfo[$i]['begin_date'],
                'end_date'   => $feeAllInfo[$i]['end_date'],
                'fee'        => yuan($feeAllInfo[$i]['fee']),
            ];
            unset($nickname);
        }
        return $returnData;
    }

//    public function test()
//    {
//        $billModel = new BillManager();
//        $messageModel = new MessageTemplate();
//        $payNoticeModel = new PayNotice();
//        $leaseModel = new Lease();
//        $userlist = $leaseModel->getContractInfo(['building_id' => 93], 'tenant_id, finance_mobile, ordernum');
//        $count = count($userlist);
//        for ($i=0;$i<$count;$i++) {
//            $tenantId = $userlist[$i]['tenant_id'];
//            $financeMobile = $userlist[$i]['finance_mobile'];
//            $ordernum = $userlist[$i]['ordernum'];
//
//            $bill = $billModel->getPayBillList(['tenant_id' =>$tenantId, 'is_delete' => 0]);
//            //再生成对应的催缴用户信息模板
//
//            $baseTmp      = $messageModel->getTemplateByPayOrIncome(1, 1, 1);//租赁账单 催缴 付款人,获取基本的模板信息
//            if (!$baseTmp) {
//                zft_log('message/get', $messageModel->getLastSql());
//                $this->apiReturn(400, [], '用户消息模板保存失败');
//            }
//
//            $payNoticeData = $insertNotice = [];
//            $tmp = [];
//            foreach ($bill as $b) {
//                //同一个时段一个用户, 重复的去掉
//                $t = [$tenantId, $b['begin_cycle'], $b['end_cycle']];
//                if (in_array($t, $tmp)) {
//                    continue;
//                } else {
//                    $tmp[] = $t;
//                    $payNoticeData[] = [
//                        'mid'           => $tenantId,
//                        'tmp_id'        => $baseTmp[0]['id'],
//                        'ordernum'      => $ordernum,
//                        'begin_cycle'   => $b['begin_cycle'],
//                        'end_cycle'     => $b['end_cycle'],
//                        'mobile'        => $financeMobile,
//                        'report_time'   => strtotime($b['begin_cycle']) - 86400 * $baseTmp[0]['notify_day'],
//                        'priority'      => 1,
//                        'status'        => 0,
//                    ];
//                }
//                unset($t);
//            }
//
//            foreach ($payNoticeData as $pt) {
//                if (strtotime($pt['end_cycle']) >= time()) {//比当前时间大的才加入催缴列表
//                    $insertNotice[] = $pt;
//                }
//            }
//
//            if ($insertNotice) {
//                $res = $payNoticeModel->addAll($insertNotice);
//                if (!$res) {
//                    zft_log('payNotice/addTemplate', $payNoticeModel->getLastSql());
//                    $this->apiReturn(400, [], '用户消息模板保存失败');
//                }
//            }
//        }
//    }

    /**
     * 录入合约
     * @author wuhao
     * @date   2017-01-24
     *
     * @return json
     */
    public function insertContractInfo()
    {
        if (!in_array($this->getOper('add_lease'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $industry      = I('post.industry', '', 'intval');      //行业属性
        //$ordermode     = I('post.ztype', 0, 'intval');          //合约类型0个人 1企业
        $buildingId    = I('post.building_id', 0, 'intval');    //楼宇id
        $tenantId      = I('post.tenant_id', 0, 'intval');      //租户id
        $useBillingDay = I('post.use_billing_day', 0, 'intval'); //是否按账单日生成账单
        //$tenantName    = I('post.tenant_name', '', 'strval');   //租户姓名
        //$sex           = I('post.sex', 'M', 'strval');          //性别
        $mobile        = I('post.mobile', '', 'strval');        //手机号
        //$idCard        = I('post.id_card', '', 'strval');       //身份证id
        $idCardA       = I('post.id_card_a', '', 'strval');     //身份证正面
        $idCardB       = I('post.id_card_b', '', 'strval');     //身份证反面
        //$address       = I('post.address', '', 'strval');       //地址
        $contractTime  = I('post.contract_time', '', 'strval');   //签约时间 20170515
        $beginTime     = I('post.begin_time', '', 'intval');    //开始租赁 20170515
        $endTime       = I('post.end_time', '', 'intval');      //结束租赁 20170515
        $chargeType    = I('post.charge_type', 1, 'intval');    //收费周期 1月 2季度 3半年 4年
        $billingDay    = I('post.billing_day', '', 'intval');   //账单日
        $tax           = I('post.tax', 0, 'floatval');          //税,默认为0
        $freeDay       = I('post.free_day', 0, 'intval');       //免租期天数
        $legalIdCard   = I('post.legal_id_card', '', 'strval'); //法人身份证信息
        //$license       = I('post.license', '', 'strval');       //营业执照
        $financeMobile = I('post.finance_mobile', '', 'strval'); //财务联系电话
        $financeUser   = I('post.finance_user', '', 'strval');   //财务联系人名字
        $discount      = I('post.discount', 10, 'floatval');     //第一年折扣 默认10折(不打折)
        $photo         = I('post.photo', '', 'strval');         //租赁合约附件
        $growthRate    = I('post.growth_rate');                 //逐年增长率数组
        $houseNumber   = I('post.house_number');                //房源编号数组
        $feeInfo       = I('post.feeInfo');                     //合约费用数组
        $meter         = I('post.meter');                       //水电度数数组

        $growthRate    = json_decode($growthRate, true);
        $houseNumber   = json_decode($houseNumber, true);
        $feeInfo       = json_decode($feeInfo, true);
        $meter         = json_decode($meter, true);

        if (!$buildingId || !$idCardA ||!$idCardB
             ||!$beginTime ||!$endTime ||!$chargeType || !in_array($chargeType, [1,2,3,4]) ||!$billingDay || $billingDay<=0 || $billingDay >28 ||!$financeMobile
            ||!$financeUser ||!$feeInfo ||!is_array($feeInfo) || !$houseNumber || !is_array($houseNumber)) {
            $this->apiReturn(202, [], '缺少参数或参数有误');
        }
        if (!$contractTime || !strtotime($contractTime)) {
            $this->apiReturn(202, [], '签约时间必填');
        }
        if (!is_numeric($discount) || $discount <=0 || $discount>10) {
            $this->apiReturn(202, [], '折扣值有误');
        }

        if (count($houseNumber) != count($meter)) {//房子和其对应的水电度数个数不一致
            $this->apiReturn(202, [], '水电度数有误');
        } else {
            //水电度数里的房源编号与房源编号比较
            $mHouse = array_column($meter, 'house_number');
            if ($mHouse != $houseNumber) {
                $this->apiReturn(202, [], '水电度数有误');
            }

            foreach ($meter as $k => $m) {
                if (!is_numeric($m['house_number']) || !is_numeric($m['water']) || !is_numeric($m['power']) || $m['water'] <0 || $m['power']<0 || $m['house_number'] <0) {
                    $this->apiReturn(202, [], '水电度数有误');
                }
                $meter[$k]['water'] = round($m['water'] * 100);//乘以100取整
                $meter[$k]['power'] = round($m['power'] * 100);
            }
        }

        $leaseModel = new Lease();
        //判断这些房源是否已经签约
        $check = $leaseModel->getLeaseExtByHouse($houseNumber, 'id');
        if ($check) {
            $this->apiReturn(202, [], '存在房源已经签约过的了');
        }

        //检查租户信息的正确性
        $memberModel = new Member();
        $memberInfo = $memberModel->getMemberInfo(['id' => $tenantId, 'mobile' => $mobile, 'dtype' => 2], 'id, user_type');
        if (!$memberInfo) {
            $this->apiReturn(203, [], '输入的租户信息有误');
        }
        //检测房源合法性
        $houseList = $this->_checkHouse($houseNumber);
        if (!$houseList) {
            $this->apiReturn(204, [], '房源信息有误');
        }
        $ownerId = $houseList[0]['mid'];//业主id

        if ((strtotime($endTime) - (strtotime($beginTime.'+'.$freeDay.'day'))) <0) {
            $this->apiReturn(205, [], '租赁时间有误');
        }

        //开始周期作为起租日
        $beginRent = $beginTime;
        //获取合约时间长度, 判断合约时间是否合法
        $begin = date('Y-m-d', strtotime($beginRent));
        $end   = date('Y-m-d', strtotime($endTime));

        $diffDate = diffDate($begin, $end);//得到相隔年月日
        if ($diffDate['year'] >= 10) {
            $this->apiReturn(204, [], '租期不能超过10年');
        }
        //相隔年数, 月数, 季度数, 半年数
        $diffYear = $diffDate['year'] + 1;

        if ($diffYear >= 2) {
            //判断增长率是否合法
            if (!$growthRate || !is_array($growthRate) || (count($growthRate) != ($diffYear - 1))) {
                $this->apiReturn(205, [], '增长率不合法');
            }
            foreach ($growthRate as $k => $g) {
                if (!is_numeric($g) || $g < 0) {
                    $this->apiReturn(205, [], '增长率不合法');
                }
                $growthRate[$k] = intval($g*100);//增长率*100, 保存为整数
            }
        } else {
            $growthRate = [];
        }
//var_dump($feeInfo);
        $ordernum   = time().genRandomNum(2); //合同编号12位
        //判断基础费用设置
        $tmpRatio = $feeDataInfo = [];
        foreach ($feeInfo as $key => $value) {
            if ($value && $value['fee'] >=0 && $value['owner_id'] >0 && in_array($value['type'], [1,2]) && $value['ratio'] >0 && $value['ratio'] <=100) {
                $feeDataInfo[] = [
                    'ordernum' => $ordernum,
                    'fee'      => $value['fee']*100,
                    'owner_id' => $value['owner_id'],
                    'type'     => $value['type'],
                    'ratio'    => $value['ratio'],
                ];
                if (!isset($tmpRatio[$value['type']])) {//判断比例之和是否为100
                    $tmpRatio[$value['type']] = $value['ratio'];
                } else {
                    $tmpRatio[$value['type']] += $value['ratio'];
                }
            } else {
                $this->apiReturn(400, [], '费用设置有误!');
            }
        }

        foreach ($tmpRatio as $k => $v) {
            if ($v != 100) {
                $this->apiReturn(400, [], '费用比例设置有误!');
            }
        }
        //判断这些费用与对应的房源的费用是否一致
        $rentMoney = $propertyMoney = 0;
        foreach ($houseList as $h) {
            if ($h['price_type'] == 0) {//按月
                $rentMoney += $h['price'];
            } else {//按每平米
                $rentMoney += $h['price'] * $h['area'];
            }
            $propertyMoney += $h['property'] * $h['area'];
        }
        foreach ($feeDataInfo as $f) {
            if ($f['type'] ==1 && $f['fee'] != $rentMoney) {//房租
                $this->apiReturn(400, [], '房租信息不匹配!');
            }
            if ($f['type'] ==2 && $f['fee'] != $propertyMoney) {//房租
                $this->apiReturn(400, [], '物业费信息不匹配!');
            }
        }



        //有配置税率的话
        if ($tax) {
            if (!is_numeric($tax) || $tax <0 || $tax>50) {
                $this->apiReturn(400, [], '税率配置有误!');
            }
            $tax = round($tax, 2) * 100;//税*100, 保存整数
            $taxArr = [];
            foreach ($feeDataInfo as $a => $item) {
                if ($item['type'] == 1) {//税费的收费对象和房租的一致
                    $taxArr[] = [
                        'fee'      => $item['fee'] * $tax / 10000 ,//生成每个月的单价
                        'type'     => 7,
                        'owner_id' => $item['owner_id'],
                        'ratio'    => $item['ratio'],
                        'ordernum' => $ordernum,
                    ];
                }
            }
            $feeDataInfo = array_merge($feeDataInfo, $taxArr);
        }

        //折扣乘以100,保存为整数
        $discount = round($discount * 100);
        //根据基础的费用生成每个周期的费用
        if ($useBillingDay == 1) {//按账单日生成
            $feeAllInfo = $this->_generateFeeByBillingDay($feeDataInfo, $chargeType, $freeDay, $begin, $end, $discount, $growthRate, $billingDay);
        } else {//每月递增生成
            $feeAllInfo = $this->_generateFee($feeDataInfo, $chargeType, $freeDay, $begin, $end, $discount, $growthRate);
        }

        if (!$feeAllInfo) {
            $this->apiReturn(400, [], '费用信息生成失败');
        }
        
        $data = [
            'tenant_id'      => $tenantId,      //租户id
            'owner_id'       => $ownerId,       //业主id
            'create_user'    => $this->_pmid,//帮忙签约的人的id
            'building_id'    => $buildingId,    //楼宇id
            'ordernum'       => $ordernum,     //合同编号
            'industry'       => $industry,     //行业属性
            'ordermode'      => $memberInfo[0]['user_type'],    //合约类型0个人 1企业
            'ordertime'      => time(),
            'begin_time'     => $beginTime,   //合同开始时间时间
            'free_day'       => $freeDay ,   //免租天数
            'end_time'       => $endTime,     //结束租赁时间
            'charge_type'    => $chargeType,  //收费周期类型
            'lease_mode'     => 2,             //租赁方式 1托管 2租赁
            'billing_day'    => $billingDay,  //账单日 (按每周期)
            'id_card_a'      => $idCardA,    //身份证正面
            'id_card_b'      => $idCardB,    //身份证反面
            'tax'            => $tax,          //税率
            'legal_id_card'  => $legalIdCard,  //法人身份证信息
            'finance_mobile' => $financeMobile,//财务联系电话
            'finance_user'   => $financeUser,  //财务联系人姓名
            'growth_rate'    => json_encode($growthRate),//增长率
            'discount'       => $discount,      //第一年折扣率
            'contract_time'  => $contractTime   //签约时间
        ];

        //插入数据
        $leaseId = $leaseModel->insertContractInfo($data);//插入合约基本信息
        if ($leaseId) {
            //插入合约的拓展信息
            //获取房号
            $buildModel = new Building();
            $roomArr = $buildModel->getHouseList(['house_number' => ['in', $houseNumber]], 'id, house_number, number,  room');
            $extData = [];
            foreach ($meter as $key => $m) {
                $room = $number = '';
                foreach ($roomArr as $r) {
                    if ($m['house_number'] == $r['house_number']) {
                        $room = $r['room'];
                        $number = $r['number'];
                        $houseId = $r['id'];
                        break;
                    }
                }
                $extData[] = [
                    'ordernum'     => $ordernum,
                    'house_id'     => $houseId,
                    'house_number' => $m['house_number'],
                    'number'       => $number,
                    'room'         => $room,
                    'water'        => $m['water'],
                    'electric'     => $m['power'],
                    'create_time'  => time(),
                    'update_time'  => time(),
                ];
            }
            $extRes  = $leaseModel->insertExtInfo($extData);
            if (!$extRes) {
                zft_log('lease/add_lease_ext', $leaseModel->getLastSql());
                $this->apiReturn(400, [], '拓展信息保存失败');
            }
            //插入费用信息
            $feeRes = $leaseModel->insertFeeInfo($feeAllInfo);
            if (!$feeRes) {
                zft_log('lease/add_lease_fee', $leaseModel->getLastSql());
                $this->apiReturn(400, [], '费用信息保存失败');
            }
            //更新为已出租的状态
            $buildModel = new Building();
            $updateHouseRes = $buildModel->updateHouse(['status' => 1], ['house_number' => ['in', $houseNumber]]);
            if (!$updateHouseRes) {
                zft_log('lease/update_house', $buildModel->getLastSql());
                $this->apiReturn(400, [], '房屋状态更新失败');
            }

            //图片信息的保存
            if ($photo) {
                $photos = explode(',', $photo);
                $photoModel = new Photo();
                $photoInfos = [];
                foreach ($photos as $val) {
                    $photoInfos[] = [
                        'rid'         => $leaseId,
                        'rtype'       => 3,
                        'srtype'      => 1,
                        'url'         => $val,
                        'create_user' => $this->_pmid,
                        'create_time' => time(),
                    ];
                }
                $resPhoto = $photoModel->addAll($photoInfos);
                if (!$resPhoto) {
                    zft_log('photo/add_lease', $photoModel->getLastSql());
                }
            }

            //把账单生成出来
            $bill = $this->_generateBill($ordernum);
            if (!$bill) {
                $this->apiReturn(400, [], '账单生成失败');
            }
            //插入账单数据
            $billModel = new BillManager();
            $billRes   = $billModel->insertPayBill($bill);
            if (!$billRes) {
                zft_log('lease/add_bill', $billModel->getLastSql());
                $this->apiReturn(400, [], '账单生成失败');
            }

            //再生成对应的催缴用户信息模板
            $messageModel = new MessageTemplate();
            $baseTmp      = $messageModel->getTemplateByPayOrIncome(1, 1, 1);//租赁账单 催缴 付款人,获取基本的模板信息
            if (!$baseTmp) {
                zft_log('message/get', $messageModel->getLastSql());
                $this->apiReturn(400, [], '用户消息模板保存失败');
            }
            //dd($baseTmp);
            $payNoticeModel = new PayNotice();
            $payNoticeData = $insertNotice = [];
            $tmp = [];
            foreach ($bill as $b) {
                //同一个时段一个用户, 重复的去掉
                $t = [$tenantId, $b['begin_cycle'], $b['end_cycle']];
                if (in_array($t, $tmp)) {
                    continue;
                } else {
                    $tmp[] = $t;
                    $payNoticeData[] = [
                        'mid'           => $tenantId,
                        'building_id'   => $buildingId,
                        'tmp_id'        => $baseTmp[0]['id'],
                        'ordernum'      => $ordernum,
                        'begin_cycle'   => $b['begin_cycle'],
                        'end_cycle'     => $b['end_cycle'],
                        //'mobile'        => $financeMobile,
                        'report_time'   => strtotime($b['begin_cycle']) - 86400 * $baseTmp[0]['notify_day'],
                        'priority'      => 1,
                        'status'        => 0,
                    ];
                }
                unset($t);
            }

            foreach ($payNoticeData as $pt) {
                if (strtotime($pt['end_cycle']) >= time()) {//比当前时间大的才加入催缴列表
                    $insertNotice[] = $pt;
                }
            }
            if ($insertNotice) {
                $res = $payNoticeModel->addAll($insertNotice);
                if (!$res) {
                    zft_log('payNotice/addTemplate', $payNoticeModel->getLastSql());
                    $this->apiReturn(400, [], '用户消息模板保存失败');
                }
            }

            $this->apiReturn(200, [], '合约保存成功');
        } else {
            zft_log('lease/add_lease', $leaseModel->getLastSql());
            $this->apiReturn(400, [], '保存失败');
        }
    }

/*    public function test()
    {
        $feeData = [
            [
                'ordernum' => '149492838322',
                'fee' => 720800,
                'owner_id' => 32,
                'type' => 1,
                'ratio' => 100,
            ],
        ];
        $this->_generateFee($feeData, 1, 20, '2017-05-02', '2020-11-30', 1000, [400,0,500], 12);
    }*/

    /**
     * 租赁签约生成费用信息(从租赁开始按月递增生成账单)
     * @author wuhao
     * @date   2017-04-10
     *
     * @param array  $feeData    基础费用数组
     * @param int    $chargeType 收费周期 1月 2季度 3半年 4年
     * @param int    $freeDays   免租天数
     * @param string $begin      租赁收费时间 如2017-02-02
     * @param string $end        租赁结束时间 如2020-02-01
     * @param int    $discount   第一年的折扣 100表示1折 10%
     * @param array  $growthRate 第二年及之后的增长率
     * @return array
     */
    private function _generateFee(array $feeData, $chargeType, $freeDays = 0, $begin, $end, $discount, array $growthRate = [])
    {
        switch ($chargeType) {
            case 1://按月
                $monthNum = 1;
                break;
            case 2://按季度
                $monthNum = 3;
                break;
            case 3://按半年
                $monthNum = 6;
                break;
            case 4://按年
                $monthNum = 12;
                break;
            default:
                return false;
        }

        //获取基础房租和基础税费
        $baseTax = $baseRent = 0;
        foreach ($feeData as $v) {
            if ($v['type'] == 1) {
                $baseRent = $v['fee'];
            } elseif ($v['type'] == 7) {
                $baseTax = $v['fee'];
            } else {
                continue;
            }
        }

        //获取逐年的房租和税费
        $rentArr = $taxArr = [];
        if ($baseRent) {
            $rentArr = $this->_getMoney($baseRent, $discount, $growthRate);
        }
        if ($baseTax) {
            $taxArr = $this->_getMoney($baseTax, $discount, $growthRate);
        }

        //第一个周期时间
        $firstBegin = date('Ymd', strtotime($begin));
        if (strtotime($begin.'+'.$monthNum.'month-1day') < strtotime($end)) {//判断第一个周期的截止是否小于合同截止时间
            $firstEnd  = date('Ymd', strtotime($begin.'+'.$monthNum.'month-1day'));
        } else {
            $firstEnd = date('Ymd', strtotime($begin));
        }

        $data = [];
        //先保存收费周期数组
        $data[] = [
            'begin_date' => $firstBegin,
            'end_date'   => $firstEnd,
        ];

        while(1) {
            $count = count($data);
            if (strtotime($data[$count - 1]['end_date']) == strtotime($end)) {
                break;
            }
            $tmpBegin = date('Ymd', strtotime($data[$count - 1]['end_date'] . '+1day'));
            //判断截止时间会不会大于租期截止时间
            $tmpEnd   = (strtotime($tmpBegin . '+' . ($monthNum) . 'month-1day') > strtotime($end))
                ? date('Ymd', strtotime($end)) : date('Ymd', strtotime($tmpBegin . '+' . ($monthNum) . 'month-1day'));
            $data[] = [
                'begin_date' => $tmpBegin,
                'end_date'   => $tmpEnd,
            ];
            unset($count, $tmpEnd, $tmpBegin);
        }

        //算上免租期
        $beginRent = strtotime($firstBegin. '+' . $freeDays . 'days');
        foreach ($data as $k => $v) {
            if (strtotime($v['end_date']) < $beginRent) {//结束时间比算上免租期的开始时间小
                unset($data[$k]);
            } else {
                $data[$k]['begin_date'] = date('Ymd', $beginRent);
                break;
            }
        }
        $data = array_merge($data);

        //计算账单
        $feeAllInfo = [];
        $count = count($data);
        for ($i = 0; $i < $count; $i++) {
            $endDate = date('Y-m-d', strtotime($data[$i]['end_date']));
            $diffDate = diffDate($endDate, $begin);
            $year = $diffDate['year'];//判断哪一年的账单, 第一年房租和税费有折扣, 其余的有房租增长率(复利方式), year : 0=第一年  1=第二年...
            if ($count == 1) {
                //只有一条数据，不满一周期
                //最后一个账单周期
                $diffDay = (strtotime($data[$i]['end_date']) - strtotime($data[$i]['begin_date']) + 86400) / 86400;//计算这个开始时间+1月有多少天
                //计算这个周期有几天(开始时间+n月-开始时间)
                $thisDays = (strtotime($data[$i]['begin_date'].'+'.$monthNum . 'month') - strtotime($data[$i]['begin_date'])) / 86400;
            } else {
                if ($i == 0) {
                    //第一个账单周期
                    //先计算这个周期有几天
                    $diffDay = (strtotime($data[$i]['end_date']) - strtotime($data[$i]['begin_date']) + 86400) / 86400;//计算这个开始时间+1月有多少天
                    //计算这个周期有几天(截止时间-(截止时间-n月))
                    $thisDays = (strtotime($data[$i]['end_date']) - strtotime($data[$i]['end_date'].'-'.$monthNum.'month')) / 86400;
                } elseif ($i == $count -1) {
                    //最后一个账单周期
                    $diffDay = (strtotime($data[$i]['end_date']) - strtotime($data[$i]['begin_date']) + 86400) / 86400;//计算这个开始时间+1月有多少天
                    //计算这个周期有几天(开始时间+n月-开始时间)
                    $thisDays = (strtotime($data[$i]['begin_date'].'+'.$monthNum . 'month') - strtotime($data[$i]['begin_date'])) / 86400;
                }
            }
            
            foreach ($feeData as $key => $value) {
                $tmp['owner_id']    = $value['owner_id'];
                $tmp['ordernum']    = $value['ordernum'];
                $tmp['type']        = $value['type'];
                $tmp['ratio']       = $value['ratio'];
                $tmp['begin_date']  = $data[$i]['begin_date'];
                $tmp['end_date']    = $data[$i]['end_date'];
                $tmp['discount']    = $year == 0 ? $discount : 1000;
                $tmp['growth_rate'] = $year == 0 ? 0 : $growthRate[$year - 1];

                if ($i == 0 || $i == $count-1) {
                    if ($value['type'] == 1) {//房租
                        $tmp['fee'] = round($rentArr[$year] * $monthNum * $diffDay / $thisDays);
                    } elseif ($value['type'] == 7) {//税费
                        $tmp['fee'] = round($taxArr[$year] * $monthNum * $diffDay / $thisDays);
                    } elseif ($value['type'] == 2) {//物业费
                        $tmp['fee'] = round($value['fee'] * $monthNum * $diffDay / $thisDays);
                    }
                } else {
                    if ($value['type'] == 1) {//房租
                        $tmp['fee'] = round($rentArr[$year] * $monthNum);
                    } elseif ($value['type'] == 7) {//税费
                        $tmp['fee'] = round($taxArr[$year] * $monthNum);
                    } elseif ($value['type'] == 2) {//物业费
                        $tmp['fee'] = round($value['fee'] * $monthNum);
                    }
                }

                $feeAllInfo[] = $tmp;
                unset($tmp);
            }
        }
        return $feeAllInfo;
    }

    /**
     * 按照账单日生成租赁签约账单信息
     * @author wuhao
     * @date   2017-05-16
     *
     *
     * @param array  $feeData    基础费用数组
     * @param int    $chargeType 收费周期 1月 2季度 3半年 4年
     * @param int    $freeDays   免租天数
     * @param string $begin      租赁收费时间 如2017-02-02
     * @param string $end        租赁结束时间 如2020-02-01
     * @param int    $discount   第一年的折扣 100表示1折 10%
     * @param array  $growthRate 第二年及之后的增长率
     * @param int    $billingDay 账单日
     * @return array
     */
    private function _generateFeeByBillingDay(array $feeData, $chargeType, $freeDays = 0, $begin, $end, $discount, array $growthRate = [], $billingDay = 1)
    {
        switch ($chargeType) {
            case 1://按月
                $monthNum = 1;
                break;
            case 2://按季度
                $monthNum = 3;
                break;
            case 3://按半年
                $monthNum = 6;
                break;
            case 4://按年
                $monthNum = 12;
                break;
            default:
                return false;
        }

        //获取基础房租和基础税费
        $baseTax = $baseRent = 0;
        foreach ($feeData as $v) {
            if ($v['type'] == 1) {
                $baseRent = $v['fee'];
            } elseif ($v['type'] == 7) {
                $baseTax = $v['fee'];
            } else {
                continue;
            }
        }

        //获取逐年的房租和税费
        $rentArr = $taxArr = [];
        if ($baseRent) {
            $rentArr = $this->_getMoney($baseRent, $discount, $growthRate);
        }
        if ($baseTax) {
            $taxArr = $this->_getMoney($baseTax, $discount, $growthRate);
        }

        //开始计费时间计算
        $beginRent = date('Ymd', strtotime($begin. '+' . ($freeDays) . 'day'));
        $beginMonth = date('Ym', strtotime($begin. '+' . ($freeDays) . 'day'));
        $beginDay = date('d', strtotime($begin. '+' . ($freeDays) . 'day'));
        $nextTime = ($beginDay >= $billingDay) ? date('Ym', strtotime($beginMonth .'01 + '.$monthNum . 'month')) : $beginMonth;
        if ($billingDay < 10) {
            $billingDay = '0'.$billingDay;
        }
        //第一个收费周期截止时间
        $firstEnd  = date('Ymd', strtotime($nextTime . $billingDay . '-1day'));
        if (strtotime($firstEnd) > strtotime($end)) {//判断截止时间是否比firstEnd小
            $firstEnd = date('Ymd', strtotime($end));
        }
        $data = [];
        //先保存收费周期数组
        $data[] = [
            'begin_date' => $beginRent,
            'end_date'   => $firstEnd,
        ];

        while(1) {
            $count = count($data);
            if (strtotime($data[$count - 1]['end_date']) == strtotime($end)) {
                break;
            }
            $tmpBegin = date('Ymd', strtotime($data[$count - 1]['end_date'] . '+1day'));
            //判断截止时间会不会大于租期截止时间
            $tmpEnd   = (strtotime($tmpBegin . '+' . ($monthNum) . 'month-1day') > strtotime($end))
                ? date('Ymd', strtotime($end)) : date('Ymd', strtotime($tmpBegin . '+' . ($monthNum) . 'month-1day'));
            $data[] = [
                'begin_date' => $tmpBegin,
                'end_date'   => $tmpEnd,
            ];
            unset($count, $tmpEnd, $tmpBegin);
        }

        //生成账单
        $feeAllInfo = [];
        $count = count($data);
        for ($i = 0; $i < $count; $i++) {
            $beginDate = date('Y-m-d', strtotime($data[$i]['begin_date']));
            $diffDate2 = diffDate($beginDate, $begin);
            $year2 = $diffDate2['year'];//有可能有增长率夹在中间的

            $endDate = date('Y-m-d', strtotime($data[$i]['end_date']));
            $diffDate = diffDate($endDate, $begin);
            $year = $diffDate['year'];//判断哪一年的账单, 第一年房租和税费有折扣, 其余的有房租增长率(复利方式), year : 0=第一年  1=第二年...
            //先计算这个周期有几天
            $diffDay = (strtotime($data[$i]['end_date']) - strtotime($data[$i]['begin_date']) + 86400) / 86400;
            //计算这个开始时间+1月有多少天
            $thisDays = (strtotime($data[$i]['begin_date'].'+'.$monthNum.'month') - strtotime($data[$i]['begin_date'])) / 86400;
            if ($year != $year2) {
                //中间点
                $centerPoint = strtotime($begin . '+' . $year . 'year');
                //前一年周期的增长率天数
                $previousDay = ($centerPoint - strtotime($data[$i]['begin_date'])) / 86400;
                //后一年周期的天数
                $nextDay = (strtotime($data[$i]['end_date']) - $centerPoint + 86400) / 86400;
                //dd($previousDay, $nextDay, $thisDays, date('Ymd', $centerPoint));
            }

            foreach ($feeData as $key => $value) {
                $tmp['owner_id']    = $value['owner_id'];
                $tmp['ordernum']    = $value['ordernum'];
                $tmp['type']        = $value['type'];
                $tmp['ratio']       = $value['ratio'];
                $tmp['begin_date']  = $data[$i]['begin_date'];
                $tmp['end_date']    = $data[$i]['end_date'];
                $tmp['discount']    = $year == 0 ? $discount : 1000;
                $tmp['growth_rate'] = $year == 0 ? 0 : $growthRate[$year - 1];


                //房租和税费有可能有增长率夹中间的情况
                if ($year != $year2) {
                    if ($value['type'] == 1) {//房租
                        $tmp['fee'] = round($rentArr[$year2] * $monthNum * $previousDay / $thisDays + $rentArr[$year] * $monthNum * $nextDay / $thisDays);
                        //dd($rentArr[$year2] * $monthNum * $previousDay / $thisDays, $rentArr[$year] * $monthNum * $nextDay / $thisDays, $tmp['fee']);
                    } elseif ($value['type'] == 7) {//税费
                        $tmp['fee'] = round($taxArr[$year2] * $monthNum * $previousDay / $thisDays + $taxArr[$year] * $monthNum * $nextDay / $thisDays);
                    } elseif ($value['type'] == 2) {//物业费
                        $tmp['fee'] = round($value['fee'] * $monthNum * $diffDay / $thisDays);
                    }
                } else {
                    if ($value['type'] == 1) {//房租
                        $tmp['fee'] = round($rentArr[$year] * $monthNum * $diffDay / $thisDays);
                    } elseif ($value['type'] == 7) {//税费
                        $tmp['fee'] = round($taxArr[$year] * $monthNum * $diffDay / $thisDays);
                    } elseif ($value['type'] == 2) {//物业费
                        $tmp['fee'] = round($value['fee'] * $monthNum * $diffDay / $thisDays);
                    }
                }
                $feeAllInfo[] = $tmp;
                unset($tmp);
            }
        }
        return $feeAllInfo;
    }

    /**
     * 计算折扣和复利后的金额
     * @author wuhao
     * @date   2017-04-10
     *
     *
     * @param int    $fee        基础费用
     * @param int    $discount   第一年的折扣 1000表示10折 没有折扣
     * @param array  $growthRate 第二年及之后的增长率
     * @return array
     */
    private function _getMoney($fee, $discount, $growthRate = [])
    {
        if (!$fee || !$discount) {
            return false;
        }
        //相隔年数
        $years = count($growthRate) + 1;
        $data = [];
        for ($j = 0; $j < $years; $j++) {
            if ($j == 0) {
                $data[$j] = $fee;
            } else {
                $data[$j] = $data[$j-1] * ((100 + $growthRate[$j-1]/100) / 100);
            }
        }
        $data[0] = $fee * $discount / 1000;
        return $data;
    }

    /**
     * 租赁签约对应的账单的数据生成
     * @author wuhao
     * @date   2017-04-12
     *
     * @param int  $ordernum   订单id
     * @return bool|array
     */
    private function _generateBill($ordernum)
    {
        if (!$ordernum || !is_numeric($ordernum)) {
            return false;
        }
        $leaseModel = new Lease();
        //获取合约的租户,楼宇信息
        $baseInfo = $leaseModel->getLeaseByOrderNum($ordernum, 'tenant_id, building_id, charge_type');
        //获取合约的费用信息
        $feeInfo  = $leaseModel->getLeaseFeeByOrderNum($ordernum, '*');
        if ($baseInfo  && $feeInfo) {
            $data = [];
            foreach ($feeInfo as $k => $v) {
                $data[] = [
                    'ordernum'    => $ordernum,
                    'building_id' => $baseInfo['building_id'],
                    'charge_out'  => date('Ymd', time()),
                    'type'        => $baseInfo['charge_type'],
                    'begin_cycle' => $v['begin_date'],
                    'end_cycle'   => $v['end_date'],
                    'owner_id'    => $v['owner_id'],
                    'tenant_id'   => $baseInfo['tenant_id'],
                    'money'       => $v['fee'] * $v['ratio'] / 100,
                    'time'        => time(),
                    'bill_time'   => substr(trim($v['begin_date']), 0, 6),
                    'status'      => 0,
                    'type_money'  => $v['type'],
                ];
            }
            return $data;
        } else {
            return false;
        }
    }

    /**
     * 租赁签约判断所选房源的合法性
     * @author wuhao
     * @date   2017-04-10
     *
     * @param array $houseNumberArr 房源编号数组
     * @return bool|array
     */
    private function _checkHouse($houseNumberArr)
    {
        if (!$houseNumberArr || !is_array($houseNumberArr)) {
            return false;
        }
        $buildModel  = new Building();
        $houseList   = $buildModel->getHouseList(['house_number' => ['in', $houseNumberArr]], 'status, trust_status, building_id, mid, price, price_type, area, property');
        $mid         = array_unique(array_column($houseList, 'mid'));
        if (count($mid) >1 || count($mid) <=0) {//业主只能一个
            return false;
        }
        $buildingId  = array_unique(array_column($houseList, 'building_id'));
        if (count($buildingId) >1 || count($buildingId) <=0) {//房源只能在一栋楼宇内
            return false;
        }
        $status      = array_unique(array_column($houseList, 'status'));
        if (count($status) >1 || count($status) <=0) {//只能是未出租的
            return false;
        } else {
            if ($status[0] == 1) {
                return false;
            }
        }
        $trustStatus = array_unique(array_column($houseList, 'trust_status'));
        if (count($trustStatus) >1 || count($trustStatus) <=0) {//托管状态只能为一个 只能为托管房源或非托管房源
            return false;
        }
        $leaseModel = new Lease();
        $leaseInfo  = $leaseModel->getLeaseExtByHouse($houseNumberArr, 'ordernum');
        if ($leaseInfo) {
            return false;  //存在房源已经签约的了
        }
        return $houseList;
    }

    /**
     * 租赁签约判断所选房源的合法性(前端调用)
     * @author wuhao
     * @date   2017-04-10
     *
     * @param array $houseNumberArr 房源编号数组
     * @return json
     */
    public function checkHouseLegal()
    {
        $houseNumberArr = I('post.house_number');
        $houseNumberArr = json_decode($houseNumberArr, true);
        if (!$houseNumberArr || !is_array($houseNumberArr)) {
            $this->apiReturn(400, [], '参数错误');
        }
        $buildModel  = new Building();
        $houseList   = $buildModel->getHouseList(['house_number' => ['in', $houseNumberArr]], 'status, trust_status, building_id, mid');
        $mid         = array_unique(array_column($houseList, 'mid'));
        if (count($mid) >1 || count($mid) <=0) {//业主只能一个
            $this->apiReturn(201, [], '业主只能为一个');
        }
        $buildingId  = array_unique(array_column($houseList, 'building_id'));
        if (count($buildingId) >1 || count($buildingId) <=0) {//房源只能在一栋楼宇内
            $this->apiReturn(202, [], '楼宇只能为一个');
        }
        $status      = array_unique(array_column($houseList, 'status'));
        if (count($status) >1 || count($status) <=0) {//只能是未出租的
            $this->apiReturn(203, [], '已出租房源不能签约');
        } else {
            if ($status[0] == 1) {
                $this->apiReturn(203, [], '已出租房源不能签约');
            }
        }
        $trustStatus = array_unique(array_column($houseList, 'trust_status'));
        if (count($trustStatus) >1 || count($trustStatus) <=0) {//托管状态只能为一个 只能为托管房源或非托管房源
            $this->apiReturn(204, [], '所选房源存在托管房源和非托管房源');
        }
        $leaseModel = new Lease();
        $leaseInfo  = $leaseModel->getLeaseExtByHouse($houseNumberArr, 'ordernum');
        if ($leaseInfo) {
            $this->apiReturn(204, [], '所选房源已签约了');  //存在房源已经签约的了
        }
        $this->apiReturn(200, [], '');
    }


    /**
     * 修改合同
     * @date   2017-05-15
     * @author wuhao
     *
     * @param  int  $ordernum    合同编号
     *
     * @return json
     */
    public function editLease()
    {
        $ordernum = I('post.ordernum', '','strval');
        $financeUser = I('post.finance_user', '','strval');
        $financeMobile = I('post.finance_mobile', '','strval');
        if (!$ordernum || !$financeMobile || !$financeUser) {
            $this->apiReturn(400, [], '参数有误');
        }
        $leaseModel = new Lease();
        $data       = $leaseModel->getLeaseByOrdernum($ordernum, 'create_user,finance_user,finance_mobile');//获取基本信息
        if (!$data) {
            $this->apiReturn(401, [], '查不到数据');
        }
        if ($data['create_user'] != $this->_pmid) {
            $this->apiReturn(402, [], '非创建人不能修改');
        }
        if ($financeUser == $data['finance_user'] && $financeMobile == $data['finance_mobile']) {
            $this->apiReturn(403, [], '信息未作修改');
        }

        //修改信息
        if ($leaseModel->updateLease($ordernum, $financeUser, $financeMobile)) {
            $this->apiReturn(200, [], '修改成功');
        } else {
            zft_log('lease/update', $leaseModel->getLastSql());
            $this->apiReturn(201, [], '修改出错');
        }
    }

    /**
     * 模糊查询租户姓名返回租户名称和id
     * @date   2017-05-16
     * @author wuhao
     *
     * @param  string  $name   租户姓名
     *
     * @return json
     */
    public function searchTenant()
    {
        $name = I('post.name', '', 'string');
        $memberModel = new Member();
        $memberInfo = $memberModel->searchTenant($name);
        if (!$memberInfo) {
            $this->apiReturn(201, [], '没有数据');
        } else {
            $this->apiReturn(200, $memberInfo, '');
        }
    }

    /**
     * 获取租户的基本信息
     * @date   2017-05-17
     * @author wuhao
     *
     * @param  id  $id   租户id
     *
     * @return json
     */
    public function searchTenantById()
    {
        $id = I('post.id', '', 'intval');
        if (!$id) {
            $this->apiReturn(400, [], '参数错误');
        }
        $memberModel = new Member();
        $memberInfo = $memberModel->searchTenantById($id);
        if (!$memberInfo) {
            $this->apiReturn(201, [], '没有数据');
        } else {
            $this->apiReturn(200, $memberInfo, '');
        }
    }

    /**
     * 获取未处理的导入的租赁合同
     * @date   2017-06-27
     * @author wuhao
     *
     * @param  string  $buildName   楼宇名称
     * @param  string  $room        房号
     * @param  int     $page
     * @param  int     $pageSize
     *
     * @return json
     */
    public function getImportOrder()
    {
        if (!in_array($this->getOper('handle_import_list'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $buildName  = I('post.name', '', 'strval');
        $room       = I('post.room', '', 'strval');
        $page       = I('post.page', 1, 'intval');
        $pageSize   = I('post.page_size', 15, 'intval');
        if (!$page || !$pageSize || $page<=0 || $pageSize<=0) {
            $this->apiReturn(400, [], '分页参数有误');
        }
        $buildId    = [];
        $orderNum   = [];
        $buildModel = new Building();
        $leaseModel = new Lease();
        if ($buildName) {
            $tmp     = $buildModel->getBuildingList(['name' => ['like', "%$buildName%"]], 'id');
            if (!$tmp) {
                $this->apiReturn(400, [], '暂无数据');
            } else {
                $buildId = array_column($tmp, 'id');
            }
        }
        if ($room) {
            $tmpOrder = $leaseModel->getLeaseExtByRoom($room, 'ordernum', 2);
            if (!$tmpOrder) {
                $this->apiReturn(400, [], '暂无数据');
            } else {
                $orderNum = array_column($tmpOrder, 'ordernum');
            }
        }

        $res = $leaseModel->getImportOrder($buildId, $orderNum, $this->_pmid, $page, $pageSize);
        if (!$res) {
            $this->apiReturn(400, [], '暂无数据');
        }

        $resBuild  = array_column($res['list'], 'building_id');
        $resTenant = array_column($res['list'], 'tenant_id');

        //获取楼宇数据
        $resBuildName = $buildModel->getBuildingList(['id' => ['in', $resBuild]], 'id, name');
        //获取租户数据
        $memberModel  = new Member();
        $resTenantInf = $memberModel->getMemberInfoById($resTenant, 'id, nickname, mobile');
        foreach ($res['list'] as $k => $v) {
            foreach ($resBuildName as $b) {
                if ($b['id'] == $v['building_id']) {
                    $res['list'][$k]['building_name'] = $b['name'];
                    break;
                }
            }
            foreach ($resTenantInf as $t) {
                if ($t['id'] == $v['tenant_id']) {
                    $res['list'][$k]['tenant_name'] = $t['nickname'];
                    $res['list'][$k]['mobile']      = $t['mobile'];
                    break;
                }
            }
        }
        $this->apiReturn(200, $res, '');
    }

    /**
     * 获取未处理的导入的租赁合同
     * @date   2017-06-28
     * @author wuhao
     *
     * @param  string  $ordernum   合同编号
     *
     * @return json
     */
    public function importOrderDetail()
    {
        $code = 200;
        $msg  = '';
        try {
            if (!in_array($this->getOper('handle_import'), $this->_allAuth)) {
                $this->apiReturn(400,[],'无权操作');
            }
            $ordernum  = I('post.ordernum', '', 'strval');
            //$ordernum  = '149861671000';
            if (!$ordernum) {
                throw new Exception('参数有误', 400);
            }
            $leaseModel = new Lease();
            $res = $leaseModel->getImportOrderDetail($ordernum);
            if (!$res) {
                throw new Exception('暂无数据', 400);
            }
            //获取房源信息
            $buildModel = new Building();
            $bname = $buildModel->getBuildingName($res['building_id']);
            $res['building_name'] = $bname['name'];

            $memberModel = new Member();
            //获取租户信息
            $resTenantInf = $memberModel->getMemberInfoById($res['tenant_id'],
                'id, nickname, mobile, sex, address, user_type, id_card, license');
            $res['nickname'] = $resTenantInf['nickname'];
            $res['mobile']   = $resTenantInf['mobile'];
            $res['sex'] = $resTenantInf['sex'];
            $res['address']   = $resTenantInf['address'];
            $res['user_type'] = $resTenantInf['user_type'];
            $res['id_card']   = $resTenantInf['id_card'];
            $res['license']   = $resTenantInf['license'];

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
            $res  = [];
        }
        $this->apiReturn($code, $res, $msg);
    }
}
